﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;

namespace ECS.Framework
{
    public static class Utilities
    {

        public static Boolean IsNumeric(Object inputObject)
        {
            if (inputObject != null)
            {
                decimal number;
                bool result = Decimal.TryParse(inputObject.ToString(), NumberStyles.Any, null, out number);
                return result;
            }
            return false;
        }

        public static Boolean IsNegativeNumeric(Object inputObject)
        {
            if (inputObject != null)
            {
                double number = 0;
                bool result = Double.TryParse(inputObject.ToString(), NumberStyles.Any, null, out number);
                if (result && number < 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        public static Boolean IsDecimal(Object inputObject)
        {
            if (inputObject != null)
            {
                decimal number;
                bool result = Decimal.TryParse(inputObject.ToString(), NumberStyles.Any, null, out number);
                if (result && number.ToString().Contains('.'))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            return false;
        }

        public static Boolean IsDate(Object InputObject)
        {
            DateTime date;
            bool result = DateTime.TryParse(InputObject.ToString(), out date);
            return result;
        }

        public static object IsNULL(Object InputObject, Object DefaultValueIfNULL)
        {
            if (InputObject == null || InputObject == DBNull.Value)
                return DefaultValueIfNULL;
            return InputObject;
        }

        //internal static string _getCurrentCAI()
        //{
        //    var m_userId = Environment.UserName;
        //    var m_userDetail = CVX.TCRS.Framework.Authentication.Authentication.getUserAuthenticationDetailStatic(m_userId);
        //    if (m_userDetail != null) return m_userDetail.CAI;
        //    return m_userId;
        //}

        //public static string GetCurrentUser()
        //{
        //    return _getCurrentCAI();
        //}

        public static string MappingFlag(string InputString)
        {
            if (InputString.ToLower() == "y")
            {
                return "Yes";
            }
            else if (InputString.ToLower() == "n")
            {
                return "No";
            }
            else
            {
                return string.Empty;
            }
        }

        public static string DateFormatting(DateTime Date)
        {
            try
            {
                DateTime dDate = Date;
                //return dDate.ToString("dd-MMM-yyyy");
                return dDate.ToString(DateFormatString);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static string DateFormatting(int Year, int Month, int Day)
        {
            try
            {
                DateTime dDate = new DateTime(Year, Month, Day);
                //return dDate.ToString("dd-MMM-yyyy");
                return dDate.ToString(DateFormatString);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static string DateFormatting_dd_mm_yy_time(object dt)
        {
            try
            {

                string date_resouce = string.Empty;
                date_resouce = String.Format("{0:dd/MM/yy HH:mm }", dt);
                return date_resouce;
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static string DateFormatting(int Year, int Month, int Day, int Hour, int Minute, int Second)
        {
            try
            {
                DateTime dDate = new DateTime(Year, Month, Day, Hour, Minute, Second);
                //return dDate.ToString("dd-MMM-yyyy HH:mm:ss");
                return dDate.ToString(DateTimeFormatString);
            }
            catch (Exception)
            {
                return string.Empty;
            }
        }

        public static string NumericFormatting(string InputNumber, int DecimalPoint)
        {
            if (!IsNumeric(InputNumber))
            {
                return string.Empty;
            }
            decimal value = Convert.ToDecimal(InputNumber);
            return value.ToString("N" + DecimalPoint);
        }

        public static string ExponentialFormatting(string InputNumber, int DecimalPoint)
        {
            if (!IsNumeric(InputNumber))
            {
                return string.Empty;
            }
            decimal value = Convert.ToDecimal(InputNumber);
            return value.ToString("E" + DecimalPoint);
        }

        public static string PercentageFormatting(string InputNumber, int DecimalPoint)
        {
            if (!IsNumeric(InputNumber))
            {
                return string.Empty;
            }
            decimal value = Convert.ToDecimal(InputNumber);
            return value.ToString("P" + DecimalPoint);
        }

        public static string fieldFormatString(int decimalScale)
        {
            string FieldFormatString = "";
            //"{0:#,###.##;-#,###.##);0.##}"
            if (decimalScale == 0)
                FieldFormatString = "{0:#,##0";
            else
                FieldFormatString = "{0:#,##0.";
            //int decimalScale = Utils.CommonConfiguration.getDecimalSettings(base.CurrentArchiveId).Decimal_Scale;
            // Add decimal for positive value
            for (int i = 0; i < decimalScale; i++)
            {
                FieldFormatString = FieldFormatString + "0";
            }

            // Add decimal for negative value
            if (decimalScale == 0)
                FieldFormatString = FieldFormatString + ";-#,##0";
            else
                FieldFormatString = FieldFormatString + ";-#,##0.";
            for (int i = 0; i < decimalScale; i++)
            {
                FieldFormatString = FieldFormatString + "0";
            }

            // Add decimal for value 0
            if (decimalScale == 0)
                FieldFormatString = FieldFormatString + ";0";
            else
                FieldFormatString = FieldFormatString + ";0.";

            for (int i = 0; i < decimalScale; i++)
            {
                FieldFormatString = FieldFormatString + "0";
            }

            FieldFormatString = FieldFormatString + "}";
            return FieldFormatString;
        }

        public static Boolean IsFormattedDecimal(Object Text, Object Value)
        {
            bool result = false;
            string[] TextSplit = Text.ToString().Split('.');
            string[] ValueSplit = Value.ToString().Split('.');
            if (ValueSplit.Count() > 1)
            {
                if (TextSplit.Count() > 1 && (TextSplit[1].Length < ValueSplit[1].Length))
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            else
            {
                result = false;
            }
            return result;
        }

        public static string ConvertToFormattedNumber(Object inputObject, long beforeDecimalDigit, long afterDecimalDigit)
        {
            if (inputObject != null)
            {
                decimal m_number;
                bool m_result = Decimal.TryParse(inputObject.ToString(), NumberStyles.Any, null, out m_number);
                string m_maxValue = "";
                if (afterDecimalDigit == 0)
                {
                    m_maxValue = string.Format("{0}", ConvertToNumberFromLength(beforeDecimalDigit));
                }
                else
                {
                    m_maxValue = string.Format("{0}.{1}", ConvertToNumberFromLength(beforeDecimalDigit), ConvertToNumberFromLength(afterDecimalDigit));
                }
                if (m_number >= Convert.ToDecimal(m_maxValue))
                {
                    return m_maxValue;
                }
                else
                {
                    return m_number.ToString();
                }

            }
            else
            {
                return "";
            }
        }

        private static string ConvertToNumberFromLength(long length)
        {
            string m_number = "";
            for (long i = 1; i <= length; i++)
            {
                m_number += "9";
            }
            return m_number;
        }

        public static decimal convertToDecimal(object inputObject, decimal defaultValue)
        {
            decimal m_result = 0;
            if (inputObject != null)
            {
                if (!Decimal.TryParse(inputObject.ToString(), NumberStyles.Any, null, out m_result))
                {
                    m_result = defaultValue;
                }

            }
            return m_result;
        }

        /// <summary>
        /// Support format "dd-MMM-yyyy HH:mm:ss" and "dd-MMM-yyyy HH:mm:ss" only
        /// </summary>
        /// <param name="dateValue">Value of date and time to convert</param>
        /// <returns></returns>
        public static DateTime? convertToDateTime(string dateValue)
        {
            CultureInfo m_enCulture = new CultureInfo("en-US");
            DateTime m_tempDT;
            bool bIsSuccess = DateTime.TryParseExact(dateValue, DateTimeFormatString, m_enCulture, DateTimeStyles.None, out m_tempDT);

            if (!bIsSuccess)
            {
                //bIsSuccess = DateTime.TryParseExact(dateValue, "dd-MMMM-yyyy HH:mm:ss", m_enCulture, DateTimeStyles.None, out m_tempDT);
                bIsSuccess = DateTime.TryParseExact(dateValue, DateTimeFormatString, m_enCulture, DateTimeStyles.None, out m_tempDT);
            }

            if (bIsSuccess)
                return m_tempDT;
            else
                return null;
        }

        /// <summary>
        /// Get date and time format: "dd-MMM-yyyy HH:mm:ss"
        /// </summary>
        public static string DateTimeFormatString
        {
            get { return "dd-MMM-yyyy HH:mm:ss"; }
        }
        /// <summary>
        /// Get date format: "dd-MMM-yyyy"
        /// </summary>
        public static string DateFormatString
        {
            get { return "dd-MMM-yyyy"; }
        }

        ////public static DataTable ListToDataTable<T>(IList<T> lst)
        ////{
        ////    var currentDT = CreateDataTable<T>();
        ////    Type entType = typeof(T);
        ////    var properties = entType.GetProperties();
        ////    foreach (T item in lst)
        ////    {
        ////        DataRow row = currentDT.NewRow();
        ////        foreach (var prop in properties)
        ////        {
        ////            if (prop.PropertyType == typeof(Nullable<decimal>) ||
        ////                prop.PropertyType == typeof(Nullable<int>) || prop.PropertyType ==
        ////                typeof(Nullable<Int64>))
        ////            {
        ////                if (prop.GetValue(item, null) == null)
        ////                    row[prop.Name] = 0;
        ////                else
        ////                    row[prop.Name] = prop.GetValue(item, null);
        ////            }
        ////            else
        ////                row[prop.Name] = prop.GetValue(item, null);
        ////        }
        ////        currentDT.Rows.Add(row);
        ////    }
        ////    return currentDT;
        ////}

        ////public static DataTable CreateDataTable<T>()
        ////{
        ////    Type entType = typeof(T);
        ////    System.Data.DataTable tbl = new System.Data.DataTable(entType.Name);
        ////    var properties = entType.GetProperties();
        ////    foreach (var prop in properties)
        ////    {
        ////        if (prop.PropertyType == typeof(Nullable<decimal>))
        ////            tbl.Columns.Add(prop.Name, typeof(decimal));
        ////        else if (prop.PropertyType == typeof(Nullable<int>))
        ////            tbl.Columns.Add(prop.Name, typeof(int));
        ////        else if (prop.PropertyType == typeof(Nullable<Int64>))
        ////            tbl.Columns.Add(prop.Name, typeof(Int64));
        ////        else
        ////            tbl.Columns.Add(prop.Name, prop.PropertyType);
        ////    }
        ////    return tbl;
        ////}

    }
}
